package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.param.UserInterViewQuery;
import com.jinzhi.jzweb.domain.vo.userAunt.UserVO;
import com.jinzhi.jzweb.service.JazMessageService;
import com.jinzhi.jzweb.service.JazSysProjectService;
import com.jinzhi.jzweb.service.JazUserAuntService;
import com.jinzhi.sys.dao.UserDao;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazInterviewDao;
import com.jinzhi.jzweb.service.JazInterviewService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 面试邀约表
 * </pre>
 * <small> 2024-05-13 15:29:16 | Long</small>
 */
@Service
public class JazInterviewServiceImpl extends CoreServiceImpl<JazInterviewDao, JazInterviewDO> implements JazInterviewService {

    @Autowired
    private JazSysProjectService jazSysProjectService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private JazUserAuntService jazUserAuntService;

    @Autowired
    private JazMessageService jazMessageService;

    /**
     * 后台-分页查询面试邀约列表
     *
     * @param userInterViewQuery
     * @return
     */
    @Override
    public Page<JazInterviewDO> getUserInterviewPage(UserInterViewQuery userInterViewQuery) {
        Page<JazInterviewDO> page = new Page<>(userInterViewQuery.getPageNumber(),userInterViewQuery.getPageSize());
        Wrapper wrapper  = new EntityWrapper().eq(Objects.nonNull(userInterViewQuery.getStatus()),"status",userInterViewQuery.getStatus())
                .orderBy("create_time",false);
        Page<JazInterviewDO> jazUserInterview =  selectPage(page,wrapper);
        //查询邀约人信息
        List<Long> userIds = jazUserInterview.getRecords().stream().filter(a -> Objects.nonNull(a.getInviterId())).
                map(JazInterviewDO::getInviterId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(userIds)){
            return jazUserInterview;
        }
        //拼接用户姓名
        List<UserDO> userDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds).
                like(StringUtil.notEmpty(userInterViewQuery.getInviterName()),"nickname",userInterViewQuery.getInviterName()));
        //用户信息不等于null
        if(!ObjectUtils.isEmpty(userDOS)){
            jazUserInterview.getRecords().forEach(a -> userDOS.forEach(b ->{
                if(Objects.equals(a.getInviterId(),b.getId())){
                    a.setInviterName(b.getNickname());
                    a.setInviterPhone(b.getMobile());
                }
            }));
        }
        //如果根据姓名查询查询
        if(StringUtil.notEmpty(userInterViewQuery.getInviterName())){
            jazUserInterview.setRecords(jazUserInterview.getRecords().stream().filter(a -> Objects.nonNull(a.getInviterName())).distinct().collect(Collectors.toList()));
        }

        // 查询被邀约人信息
        List<Long> userInviteeIds = jazUserInterview.getRecords().stream().filter(a -> Objects.nonNull(a.getInviteeId())).
                map(JazInterviewDO::getInviteeId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(userInviteeIds)){
            return jazUserInterview;
        }
        // 查询用户表
        List<UserDO> userInviteeDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userInviteeIds));
        //用户信息不等于null
        if(!ObjectUtils.isEmpty(userInviteeDOS)){
            jazUserInterview.getRecords().forEach(a -> userInviteeDOS.forEach(b ->{
                if(Objects.equals(a.getInviteeId(),b.getId())){
                    a.setInviteeName(b.getName());
                    a.setInviteePhone(b.getMobile());
                }
            }));
        }

        //查询项目类型
        List<String> projectIds = jazUserInterview.getRecords().stream().filter(a ->Objects.nonNull(a.getProjectId()))
                .map(JazInterviewDO::getProjectId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(projectIds)){
            return jazUserInterview;
        }
        List<String> projectIds1 = new ArrayList<>();
        for (int i = 0; i < projectIds.size(); i++) {
            projectIds1.addAll(Arrays.asList(projectIds.get(i).split(",")));
        }
        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projectIds1));
        jazUserInterview.getRecords().forEach(a-> {
            a.setProjectName(jazSysProjectDOS.stream().filter(b -> Objects.nonNull(a.getProjectId())).
                    filter(b -> a.getProjectId().contains(b.getId().toString())).
                    map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        });
        return jazUserInterview;
    }

    /**
     * 后台 根据id查询详情
     *
     * @param id
     * @return
     */
    @Override
    public JazInterviewDO getUserInterviewById(Long id) {
        if (id == null){
            return null;
        }
        // 查询面试信息
        JazInterviewDO jazInterviewDO = selectById(id);
        if (jazInterviewDO == null){
            return null;
        }
        // 判断面试方式显示面试地址
        if (jazInterviewDO.getInterviewFormat()==1){
            jazInterviewDO.setInterviewAddress(null);
        }
        // 根据面试信息封装邀约人信息
        if (jazInterviewDO.getInviterId()!=null){
            UserDO userDO = userDao.selectById(jazInterviewDO.getInviterId());
            if (userDO!=null){
                jazInterviewDO.setInviterName(userDO.getNickname());
                jazInterviewDO.setInviterPhone(userDO.getMobile());
            }
        }
        // 根据面试信息封装被邀约人信息
        if (jazInterviewDO.getInviteeId()!=null){
            UserDO userDO = userDao.selectById(jazInterviewDO.getInviteeId());
            if (userDO!=null){
                jazInterviewDO.setInviteeName(userDO.getName());
                jazInterviewDO.setInviteePhone(userDO.getMobile());
            }
            JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>().eq("sys_userid", jazInterviewDO.getInviteeId()));
            if (jazUserAuntDO!=null){
                //查询被邀约人项目类型
                if(StringUtil.notEmpty(jazUserAuntDO.getProjectId())){
                    String[] projects = jazUserAuntDO.getProjectId().split(",");
                    List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                    jazInterviewDO.setInviteeProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
                }
            }
        }
        //查询邀约人项目类型
        if(StringUtil.notEmpty(jazInterviewDO.getProjectId())){
            String[] projects = jazInterviewDO.getProjectId().split(",");
            List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
            jazInterviewDO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        }
        return jazInterviewDO;
    }

    /**
     * 面试邀约-确认推送
     *
     * @param jazInterviewDO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result userInterviewPush(JazInterviewDO jazInterviewDO) {
        if (jazInterviewDO==null){
            return null;
        }
        // 获取已推送的id
        JazInterviewDO interviewDO = this.selectById(jazInterviewDO.getId());
        if (jazInterviewDO!=null){
            StringBuffer buffer=new StringBuffer();
            String pushUserId = interviewDO.getPushUserId();
            if (StringUtil.notEmpty(pushUserId)){
                buffer.append(pushUserId).append(",").append(jazInterviewDO.getInviteeId());
                jazInterviewDO.setPushUserId(buffer.toString());
            }else {
                jazInterviewDO.setPushUserId(jazInterviewDO.getInviteeId().toString());
            }
        }
        if (interviewDO==null){
            return Result.fail();
        }

        interviewDO.setStatus(1);
        interviewDO.setResult(0);
        interviewDO.setInviteeId(jazInterviewDO.getInviteeId());
        interviewDO.setCancelReason("");
        interviewDO.setInterStatus(0);
        boolean update = this.updateById(interviewDO);

        // 查询月嫂id
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>().eq("sys_userid", interviewDO.getInviteeId()));
        if (jazUserAuntDO == null){
            return Result.fail();
        }

        // 发送消息
        if (interviewDO.getDemandId()!=null){
            // 邀约人
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(2);
            jazMessageDO1.setSenderId(interviewDO.getInviteeId());
            jazMessageDO1.setReceiverId(interviewDO.getInviterId());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_201.getMsg());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_201.getNum());
            jazMessageDO1.setDemandId(interviewDO.getDemandId());
            jazMessageDO1.setAuntId(jazUserAuntDO.getId());
            jazMessageDO1.setIsRead(0);
            // 被邀约人
            JazMessageDO jazMessageDO2 = new JazMessageDO();
            jazMessageDO2.setMessageType(2);
            jazMessageDO2.setSenderId(interviewDO.getInviterId());
            jazMessageDO2.setReceiverId(interviewDO.getInviteeId());
            jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_204.getMsg());
            jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_204.getNum());
            jazMessageDO2.setHasSendSms(true);
            jazMessageDO2.setDemandId(interviewDO.getDemandId());
            jazMessageDO2.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
            jazMessageService.senMessage(jazMessageDO2);
        }else {
            // 邀约人
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(2);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(interviewDO.getInviterId());
            jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_201.getMsg());
            jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_201.getNum());
            jazMessageDO1.setInterviewId(interviewDO.getId());
            jazMessageDO1.setAuntId(jazUserAuntDO.getId());
            jazMessageDO1.setIsRead(0);
            // 被邀约人
            JazMessageDO jazMessageDO2 = new JazMessageDO();
            jazMessageDO2.setMessageType(2);
            jazMessageDO2.setSenderId(ShiroUtils.getUserId());
            jazMessageDO2.setReceiverId(jazInterviewDO.getInviteeId());
            jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_204.getMsg());
            jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_204.getNum());
            jazMessageDO2.setHasSendSms(true);
            jazMessageDO2.setInterviewId(interviewDO.getId());
            jazMessageDO2.setIsRead(0);
            jazMessageService.senMessage(jazMessageDO1);
            jazMessageService.senMessage(jazMessageDO2);
        }
        return update?Result.ok() : Result.fail();
    }

    /**
     * 修改面试结果
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateUserInterview(JazInterviewDO jazInterviewDO) {
        if (jazInterviewDO==null){
            return Result.fail();
        }
        JazInterviewDO interviewDO = selectById(jazInterviewDO.getId());
        if (interviewDO==null){
            return Result.fail();
        }
        // 判断面试方式 线下
        //if (interviewDO.getInterviewFormat()==0){
            interviewDO.setResult(jazInterviewDO.getResult());
            interviewDO.setRejectReasion(jazInterviewDO.getRejectReasion());
        //}
        boolean update = updateById(interviewDO);
        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("sys_userid",interviewDO.getInviteeId());
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(entityWrapper);
        // 发送消息
        if (interviewDO.getDemandId()!=null){
            // 邀约人
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(2);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(interviewDO.getInviterId());
            jazMessageDO1.setDemandId(interviewDO.getDemandId());
            jazMessageDO1.setAuntId(jazUserAuntDO.getId());
            jazMessageDO1.setIsRead(0);
            // 被邀约人
            JazMessageDO jazMessageDO2 = new JazMessageDO();
            jazMessageDO2.setMessageType(1);
            jazMessageDO2.setSenderId(ShiroUtils.getUserId());
            jazMessageDO2.setReceiverId(interviewDO.getInviteeId());
            jazMessageDO2.setDemandId(interviewDO.getDemandId());
            jazMessageDO2.setIsRead(0);
            if (interviewDO.getResult()==0){
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"待定，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_209.getMsg()+"待定，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_209.getNum());
            } else if (interviewDO.getResult()==1) {
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"通过，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_209.getMsg()+"，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_209.getNum());
            } else if (interviewDO.getResult()==2) {
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"拒绝，拒绝原因为"+jazInterviewDO.getRejectReasion()+"，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_211.getMsg()+"，拒绝原因为"+jazInterviewDO.getRejectReasion()+"，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_211.getNum());
            }
            jazMessageService.senMessage(jazMessageDO1);
            jazMessageService.senMessage(jazMessageDO2);
        }else {
            // 邀约人
            JazMessageDO jazMessageDO1 = new JazMessageDO();
            jazMessageDO1.setMessageType(2);
            jazMessageDO1.setSenderId(ShiroUtils.getUserId());
            jazMessageDO1.setReceiverId(interviewDO.getInviterId());
            jazMessageDO1.setAuntId(jazUserAuntDO.getId());
            jazMessageDO1.setInterviewId(interviewDO.getId());
            jazMessageDO1.setIsRead(0);
            // 被邀约人
            JazMessageDO jazMessageDO2 = new JazMessageDO();
            jazMessageDO2.setMessageType(1);
            jazMessageDO2.setSenderId(ShiroUtils.getUserId());
            jazMessageDO2.setReceiverId(interviewDO.getInviteeId());
            jazMessageDO2.setInterviewId(interviewDO.getId());
            jazMessageDO2.setIsRead(0);
            if (interviewDO.getResult()==0){
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"待定，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_209.getMsg()+"待定，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_209.getNum());
            } else if (interviewDO.getResult()==1) {
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"通过，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_209.getMsg()+"，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_209.getNum());
            } else if (interviewDO.getResult()==2) {
                jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_210.getMsg()+"，拒绝原因为"+jazInterviewDO.getRejectReasion()+"，请及时查看!");
                jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_211.getMsg()+"，拒绝原因为"+jazInterviewDO.getRejectReasion()+"，请及时查看!");
                jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_210.getNum());
                jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_211.getNum());
            }
            jazMessageService.senMessage(jazMessageDO1);
            jazMessageService.senMessage(jazMessageDO2);
        }
        return update?Result.ok() : Result.fail();
    }

    /**
     * 查询所有的月嫂信息
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<UserVO> getUserInterviewAunt(Long id,Long inviterId,String projectId,Long inviteeId) {
        List<UserVO> userVOList = new ArrayList<>();
        // 获取已通过审核的阿姨的信息
        List<JazUserAuntDO> jazUserAuntDOList = jazUserAuntService.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",1)
                .eq("audit_result",0).eq("enable_status",1));
        // 过滤相应类型的阿姨
        Set<String> projectIdsSet = Arrays.stream(projectId.split(","))
                .map(String::trim)
                .collect(Collectors.toSet());
        List<JazUserAuntDO> filteredList = jazUserAuntDOList.stream()
                // 过滤条件：jazUserAuntDO.getProjectId()中的每一个ID都在projectIdsSet中存在
                .filter(jazUserAuntDO -> {
                    Set<String> auntProjectIdsSet = Arrays.stream(jazUserAuntDO.getProjectId().split(","))
                            .map(String::trim)
                            .collect(Collectors.toSet());
                    return !Collections.disjoint(auntProjectIdsSet, projectIdsSet);  // 只包含一个id就能查出
                    //return projectIdsSet.containsAll(auntProjectIdsSet);  // 包含全部的id才能查出
                })
                .collect(Collectors.toList());
        // 获取已邀请过的阿姨
        List<JazUserAuntDO> userAuntDOList =new ArrayList<>();
        JazInterviewDO jazInterviewDO = selectById(id);
/*        if (jazInterviewDO == null){
            return null;
        }
        // 面试通过-阿姨通过邀约剔除
        if (jazInterviewDO.getInterStatus()==1 && jazInterviewDO.getStatus()==1){
            // 将面试通过和邀约通过的设置进去
            if (StringUtil.notEmpty(jazInterviewDO.getPushUserId())){
                jazInterviewDO.setPushUserId(jazInterviewDO.getPushUserId()+","+String.valueOf(jazInterviewDO.getId()));
            }else {
                jazInterviewDO.setPushUserId(String.valueOf(jazInterviewDO.getId()));
            }
            updateById(jazInterviewDO);
            if (StringUtil.notEmpty(jazInterviewDO.getPushUserId())){
                Set<String> collect = Arrays.stream(jazInterviewDO.getPushUserId().split(","))
                        .map(String::trim)
                        .collect(Collectors.toSet());
                collect.remove(jazInterviewDO.getInviteeId().toString());
                userAuntDOList = filteredList.stream()
                        .filter(jazUserAuntDO -> !collect.contains(jazUserAuntDO.getSysUserid().toString()))
                        .collect(Collectors.toList());
            }
        }*/
        if (jazInterviewDO != null && StringUtil.notEmpty(jazInterviewDO.getPushUserId())){
            Set<String> collect = Arrays.stream(jazInterviewDO.getPushUserId().split(","))
                    .map(String::trim)
                    .collect(Collectors.toSet());
            collect.remove(jazInterviewDO.getInviteeId().toString());
            userAuntDOList = filteredList.stream()
                    .filter(jazUserAuntDO -> !collect.contains(jazUserAuntDO.getSysUserid().toString()))
                    .collect(Collectors.toList());
        }
        // 判断过滤后的阿姨数量
        if (userAuntDOList.size()<=0){
            // 获取所有的阿姨的用户表id
            filteredList.stream().forEach(userAunt->{
                UserVO userVO = new UserVO();
                UserDO userDO = userService.selectById(userAunt.getSysUserid());
                userVO.setSex(userDO.getSex());
                if (StringUtil.notEmpty(userDO.getName())){
                    userVO.setName(userDO.getName());
                }
                userVO.setSysUserid(userDO.getId());
                if(StringUtil.notEmpty(userDO.getOrderPhone())){
                    userVO.setMobile(userDO.getOrderPhone());
                }else {
                    userVO.setMobile("");
                }
                userVO.setProjectId(userAunt.getProjectId());
                if(StringUtil.notEmpty(userAunt.getProjectId())){
                    String[] projects = userAunt.getProjectId().split(",");
                    List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                    userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
                }
                userVOList.add(userVO);
            });
        }else {
            // 获取所有的阿姨的用户表id
            userAuntDOList.stream().forEach(userAunt->{
                UserVO userVO = new UserVO();
                UserDO userDO = userService.selectById(userAunt.getSysUserid());
                userVO.setSex(userDO.getSex());
                if (StringUtil.notEmpty(userDO.getName())){
                    userVO.setName(userDO.getName());
                }
                userVO.setSysUserid(userDO.getId());
                if(StringUtil.notEmpty(userDO.getOrderPhone())){
                    userVO.setMobile(userDO.getOrderPhone());
                }else {
                    userVO.setMobile("");
                }
                userVO.setProjectId(userAunt.getProjectId());
                if(StringUtil.notEmpty(userAunt.getProjectId())){
                    String[] projects = userAunt.getProjectId().split(",");
                    List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                    userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
                }
                userVOList.add(userVO);
            });
        }
        return userVOList;
    }


}
